#ifndef _NET_EPOLLPOLLER_H_
#define _NET_EPOLLPOLLER_H_

class EpollPoller{
public:
	struct EpollData{
		int ep_fd;
		struct epoll_event *events;
	};

	EpollPoller(EventLoop* event_loop){
		
	}

	~EpollPoller(){

	}

	int add_event(int fd, int mask){
		struct epoll_event ee;
		int ser_mask = event_loop->get_file_events(fd);
	    int op = ser_mask == AE_NONE ?
	            EPOLL_CTL_ADD : EPOLL_CTL_MOD;
	    ee.events = 0;
	    mask |= eventLoop->events[fd].mask;
	    if (mask & AE_READABLE) ee.events |= EPOLLIN;
	    if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;
	    ee.data.u64 = 0; 
	    ee.data.fd = fd;
	    if (epoll_ctl(epoll_data.epfd, op, fd, &ee) == -1) return -1;
	    return 0;
	}

	int del_event(int fd, int mask){
	    struct epoll_event ee;
	    int ser_mask = event_loop->get_file_events(fd);
	    int mask = ser_mask & (~delmask);

	    ee.events = 0;
	    if (mask & AE_READABLE) ee.events |= EPOLLIN;
	    if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;
	    ee.data.u64 = 0; 
	    ee.data.fd = fd;
	    if (mask != AE_NONE) {
	        epoll_ctl(state->epfd,EPOLL_CTL_MOD,fd,&ee);
	    } else {
	        epoll_ctl(state->epfd,EPOLL_CTL_DEL,fd,&ee);
	    }
	}

	int poll(struct timeval *tvp){
    	int retval, numevents = 0;

	    retval = epoll_wait(state->epfd, state->events, eventLoop->setsize,
	            tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1);
	    if (retval > 0) {
	        int j;
	        numevents = retval;
	        for (j = 0; j < numevents; j++) {
	            int mask = 0;
	            struct epoll_event *e = state->events+j;
                
	            if (e->events & EPOLLIN) mask |= AE_READABLE;
	            if (e->events & EPOLLOUT) mask |= AE_WRITABLE;
	            if (e->events & EPOLLERR) mask |= AE_WRITABLE;
	            if (e->events & EPOLLHUP) mask |= AE_WRITABLE;
	            eventLoop->fired[j].fd = e->data.fd;
	            eventLoop->fired[j].mask = mask;
	        }
	    }
	    return numevents;
	}

	int open(int max_event_size = 1024*1024){
		epoll_data.events = (struct epoll_event*)malloc(max_event_size);
		if(!epoll_data.events){
			return -1;
		}
		epoll_data.ep_fd = epoll_create(1024);
		if( epoll_data.ep_fd != -1){
			free(epoll_data.events);
			return -1;
		}
		return 0;
	}

	void close(){
		close(epoll_data.epfd);
		if (epoll_data.events){
			free(epoll_data.events)
		}
	}

private:
	EpollData epoll_data;
	EventLoop* event_loop;
};

#endif

